var origin = window.location.origin
// var origin = 'https://nqct.ip58.lhyw.net'

var host = origin
var dir = '/youmai';

var gethost = origin + '/awy6-youmai-service-1.0/api/a'

var signKey = 'U2FsdDSAwqwc34121ss1';
var PAGESIZE = 10; // 分页显示条数
var SEXDINC = ['女', '男'];
var CONSUTATIONTYPE = ['线下就诊', '在线就诊'];
var customUrl = 'https://tb.53kf.com/code/client/96d8f960b261e49515450f8953b044bc5/1';
var appId = 'wx44ad3c61013188de';
var avatar = './image/share-avatar.png' // 默认头像
$('.mycomment_head img').attr('src', avatar)
// 设置toast提示时间
$.toast.prototype.defaults.duration = 1500;

// toast提示
function toast(text) {
    $.toast(text, "text");
}

// jquery获取对象参数
$.fn.serializeObject = function () {
    const optionArray = $(this).serializeArray();
    const optionObject = {};
    optionArray.forEach(function (item) {
        if (optionObject[item.name] != null) {
            if (!optionObject[item.name].push) {
                optionObject[item.name] = [optionObject[item.name]];
            }
            optionObject[item.name].push($.trim(item.value));
        } else {
            optionObject[item.name] = $.trim(item.value) || '';
        }

    })
    return optionObject
}

// 空值验证
function validEmpty(value, text) {
    if (value == null || value === '') {
        toast(text);
        return true
    }
    return false
}

// 手机号验证
function validPhone(phone) {
    var reg = /^1[3456789]\d{9}$/;
    if (!reg.test(phone)) {
        toast('手机号格式错误');
        return true
    }
    return false
}

// 密码验证
function validPass(password) {
    if (/[\da-zA-Z]{8,16}/.test(password)) {
        return true
    } else {
        toast('密码为8-16位数字或字母组合');
        return false;
    }
}

// 设置cookie
function setCookie(key, val, time) {
    if (time === '' || time == undefined) { //time为空
        document.cookie = key + "=" + val + "; path=/"; //设置cookie
    } else { //设置cookie留存时间
        var date = new Date(); //获取当前时间
        date.setTime(date.getTime() + time * 24 * 3600 * 1000); //将date设置为n天以后的时间
        document.cookie = key + "=" + val + ";expires=" + date.toGMTString() + ";path=/";
    }
}

// 获取cookie的值
function getCookie(key) {
    /*获取cookie参数*/
    var arrCookie = document.cookie.replace(/[ ]/g, "").split(";"); //获取cookie，去掉空格字符, 转成数组
    var tips; //声明变量tips
    for (var i = 0; i < arrCookie.length; i++) { //使用for循环查找cookie中的tips变量
        var arr = arrCookie[i].split("="); //将单条cookie用"等号"为标识，将单条cookie保存为arr数组
        if (key == arr[0]) { //匹配变量名称，其中arr[0]是指的cookie名称，如果该条变量为tips则执行判断语句中的赋值操作
            tips = arr[1]; //将cookie的值赋给变量tips
            break; //终止for循环遍历
        }
    }
    return tips;
}

// 删除cookie的值
function delCookie(key) {
    setCookie(key, '', -10);
}

// 获取URL参数
function getQueryString(name) {
    var reg = new RegExp('[?&]' + name + '=([^&]*)(&|$)', 'gi');
    var result = reg.exec(window.location.search);
    return null != result ? result[1] : ''; // hxl null=>''
}

// hxl 过滤split，应该只有curriculum-index/video 能用得上。
function sortFilter(val, splitVal, index) {
    if (val.length == 0) {
        return ''
    } else {
        return val.split(splitVal)[index]
    }
}

// 手机号脱敏
function phoneDesensitization(phone) {
    return phone ? phone.replace(/^(\d{3})\d*(\d{4})$/, '$1****$2') : '';
}
// 身份证号脱敏
function cardDesensitization(cardId) {
    return cardId ? cardId.replace(/^(\d{7})\d*(\d{4})$/, '$1**********$2') : '';
}

// 格式化日期
function format(date) {
    if (date == null || date == '') {
        return '';
    }
    // var date = new Date(date),
    //     year = date.getFullYear(),
    //     month = date.getMonth() + 1,
    //     day = date.getDate()
    // return year + '-' + fmt(month) + '-' + fmt(day);
    return date.substr(0, 10);
}
// 格式化日期
function format1(date) {
    if (date == null || date == '') {
        return '';
    }
    var date = new Date(date),
        year = date.getFullYear(),
        month = date.getMonth() + 1,
        day = date.getDate()
    return year + '-' + fmt(month) + '-' + fmt(day);
}

function fmt(d) {
    return d < 10 ? '0' + d : d;
}

// http请求封装
var http = function (url, importOptions) {
    // 默认参数
    var defaultOption = {
        method: 'POST',
        dataType: 'json',
        hasToken: true,
        noEncry: false,
        loading: false,
        showAlert: false,
        contentType: 'application/json',
        data: {},
        success: function () { },
        fail: function () { },
        complete: function () { }
    };
    // 参数合并
    var options = $.extend({}, defaultOption, importOptions);

    // 显示loading
    if (options.loading) {
        $.showLoading();
    }

    // 去掉值为空的参数
    var data = options.data;
    for (var k in data) {
        if (data[k] == null || data[k] === '') {
            delete data[k]
        }
    }

    // 请求参数添加token
    if (options.hasToken) {
        var token = getCookie('token');
        if (!token) {
            window.location.href = 'login-code.html';
            return false;
        }
        data.token = token;
        data.userId = getCookie('userId');
    }

    // md5加密
    if (!options.noEncry) {
        data.timeStamp = new Date().getTime().toString();
        // data.timeStamp = "1624864460042";
        data.signKey = signKey;
        dataString = '{'
        Object.keys(data).sort().forEach(function (item, index) {
            if (index != 0) {
                dataString += ','
            }
            if (typeof data[item] === 'number') {
                dataString += '"' + item + '"' + ':' + data[item];
            } else {
                dataString += '"' + item + '"' + ':"' + data[item] + '"';
            }
        })
        dataString += '}';
        data.sign = md5(encodeURIComponent(dataString));
    }

    delete data.signKey;
    data = JSON.stringify(options.data);

    // 发送请求
    $.ajax({
        url: host + url,
        method: options.method,
        dataType: options.dataType,
        data: data,
        contentType: options.contentType,
        success: function (res) {
            if (options.loading) {
                $.hideLoading();
            }
            if (res.code !== '01') {
                toast(res.message || res.data)
                if (res.code === '03' && options.hasToken) {
                    window.location.href = 'login-code.html';
                }
                if (options.showAlert) {
                    $('body').html(dataString).css('word-break', 'break-all');
                    return false;
                }
            } else {
                removeNull(res.data)
            }
            options.success(res)
        },
        fail: function (err) {
            if (options.loading) {
                $.hideLoading();
            }
            toast("网络连接超时，请稍后重试");
            options.fail(err)
        },
        complete: function (res) {
            options.complete(res);

        }
    })
}

//  1.3 get请求
var gethttp = function (url, importOptions) {
    // 默认参数
    var defaultOption = {
        method: 'GET',
        dataType: 'json',
        hasToken: false,
        noEncry: false,
        loading: false,
        contentType: 'application/json',
        data: {},
        success: function () { },
        fail: function () { },
        complete: function () { }
    };
    // 参数合并
    var options = $.extend({}, defaultOption, importOptions);
    // 显示loading
    if (options.loading) {
        $.showLoading();
    }

    // 请求参数添加token
    if (options.hasToken) {
        var token = getCookie('token');
        var user = getCookie('userId');
        if (!token || !user) {
            window.location.href = 'login-code.html';
            return false;
        }
        // data.token = token;
        // data.userId = getCookie('userId');
    }
    // 发送请求
    $.ajax({
        url: gethost + url,
        method: options.method,
        dataType: options.dataType,
        data: options.data,
        contentType: options.contentType,
        success: function (res) {
            if (options.loading) {
                $.hideLoading();
            }
            if (res.code !== '01') {
                toast(res.message || res.data)
                if (res.code === '03' && options.hasToken) {
                    window.location.href = 'login-code.html';
                }
            } else {
                removeNull(res.data)
            }
            options.success(res)
        },
        fail: function (err) {
            if (options.loading) {
                $.hideLoading();
            }
            toast("网络连接超时，请稍后重试");
            options.fail(err)
        },
        complete: function (res) {
            options.complete(res);

        }
    })
}

// 1.3 
// post http请求封装
var posthttp = function (url, importOptions) {
    // 默认参数
    var defaultOption = {
        method: 'POST',
        dataType: 'json',
        hasToken: false,
        noEncry: false,
        loading: false,
        contentType: 'application/json',
        data: {},
        success: function () { },
        fail: function () { },
        complete: function () { }
    };
    // 参数合并
    var options = $.extend({}, defaultOption, importOptions);

    // 显示loading
    if (options.loading) {
        $.showLoading();
    }

    // 去掉值为空的参数
    var data = options.data;
    for (var k in data) {
        if (data[k] == null || data[k] === '') {
            delete data[k]
        }
    }

    // 请求参数添加token
    if (options.hasToken) {
        var token = getCookie('token');
        var user = getCookie('userId');
        if (!token || !user) {
            window.location.href = 'login-code.html';
            return false;
        }
        // data.token = token;
        // data.user = getCookie('userId');
    }
    data = JSON.stringify(options.data);

    // 发送请求
    $.ajax({
        url: gethost + url + '?type=c',
        method: options.method,
        dataType: options.dataType,
        data: data,
        contentType: options.contentType,
        success: function (res) {
            if (options.loading) {
                $.hideLoading();
            }
            if (res.code !== '01') {
                toast(res.message || res.data)
                if (res.code === '03' && options.hasToken) {
                    window.location.href = 'login-code.html';
                }
            } else {
                removeNull(res.data)
            }
            options.success(res)
        },
        fail: function (err) {
            if (options.loading) {
                $.hideLoading();
            }
            toast("网络连接超时，请稍后重试");
            options.fail(err)
        },
        complete: function (res) {
            options.complete(res);

        }
    })
}
var puthttp = function (url, importOptions) {
    // 默认参数
    var defaultOption = {
        method: 'PUT',
        dataType: 'json',
        hasToken: false,
        noEncry: false,
        loading: false,
        contentType: 'application/json',
        data: {},
        success: function () { },
        fail: function () { },
        complete: function () { }
    };
    // 参数合并
    var options = $.extend({}, defaultOption, importOptions);

    // 显示loading
    if (options.loading) {
        $.showLoading();
    }

    // 去掉值为空的参数
    var data = options.data;
    for (var k in data) {
        if (data[k] == null || data[k] === '') {
            delete data[k]
        }
    }

    // 请求参数添加token
    if (options.hasToken) {
        var token = getCookie('token');
        if (!token) {
            window.location.href = 'login-code.html';
            return false;
        }
        data.token = token;
        data.user = getCookie('userId');
    }

    // md5加密
    if (!options.noEncry) {
        data.timeStamp = new Date().getTime().toString();
        // data.timeStamp = "161846293736";
        data.signKey = signKey;
        dataString = '{'
        Object.keys(data).sort().forEach(function (item, index) {
            if (index != 0) {
                dataString += ','
            }
            if (typeof data[item] === 'number') {
                dataString += '"' + item + '"' + ':' + data[item];
            } else {
                dataString += '"' + item + '"' + ':"' + data[item] + '"';
            }
        })
        dataString += '}';
        data.sign = md5(dataString);
    }

    delete data.signKey;
    data = JSON.stringify(options.data);

    // 发送请求
    $.ajax({
        url: gethost + url,
        method: options.method,
        dataType: options.dataType,
        data: data,
        contentType: options.contentType,
        success: function (res) {
            if (options.loading) {
                $.hideLoading();
            }
            if (res.code !== '01') {
                toast(res.message || res.data)
                if (res.code === '03' && options.hasToken) {
                    window.location.href = 'login-code.html';
                }
            } else {
                removeNull(res.data)
            }
            options.success(res)
        },
        fail: function (err) {
            if (options.loading) {
                $.hideLoading();
            }
            toast("网络连接超时，请稍后重试");
            options.fail(err)
        },
        complete: function (res) {
            options.complete(res);

        }
    })
}

// 处理空值
function removeNull(data, str) {
    str = str || '';
    if (data == null || data == 'null' || data == '') {
        return str;
    }
    if (typeof data != 'object') {
        return data;
    }
    for (var k in data) {
        if (data[k] == null || data[k] == 'null' || data == '') {
            data[k] = str;
        }
        if (typeof data[k] == 'object') {
            removeNull(data[k])
        }
    }
}

// 清空倒计时信息
function closePopup() {
    sendStatus = false;
    $('[name=loginMobile]').val('');
    $('[name=checkCode]').val('');
    $('#getCodeBth').html('获取验证码');
    clearTimeout(timer);
}
// 倒计时
var timer;
function countDown($ele, time) {
    console.log($ele, time)
    if (--time <= 0) {
        sendStatus = false;
        $ele.html('获取验证码');
        return;
    }
    $ele.html(time + 's后重新发送');
    timer = setTimeout(function () {
        countDown($ele, time);
    }, 1000)
}

// 获取验证码
function getCode($ele, phone, type) {
    var countDownTime = 60;
    countDown($ele, countDownTime);
    // 请求接口
    http('/user/sendCheckCode', {
        hasToken: false,
        data: {
            loginMobile: phone,
            type: type,
        },
        success: function (res) {
            if (res.code === '01') {
                // lhyw.net 是公司测试环境
                if (window.location.host.indexOf('lhyw.net') > -1 || window.location.host.indexOf('localhost') > -1) {
                    $.alert(res.data, '验证码');
                }
                // toast('验证码发送成功')
            }
        }
    })
}

// 认证页切换选中项
function changeSelected($target) {
    $target.addClass('active').siblings('p').removeClass('active');
}

// 单文件上传
function singleFileUpload(file, success) {
    // 请求接口
    var formData = new FormData();
    const xhr = new XMLHttpRequest();
    formData.append("imgFile", file);
    $.showLoading('上传中..');
    $.ajax({
        url: host + '/userMessage/uploadFile',
        type: 'post',
        data: formData,
        contentType: false, //multipart/form-data
        processData: false,
        success: function (res) {
            if (res.code === '01') {
                $.hideLoading();
                success(res.data);
            } else {
                toast(res.message);
            }
        }
    })
}

// 获取上传文件路径
function getFileUrl(file) {
    var url = null;
    if (window.createObjectURL != undefined) { // basic
        url = window.createObjectURL(file);
    } else if (window.URL != undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}

// 回到讲堂首页 - 替换历史
function backIndex(delay) {
    delay = delay || 0;
    setTimeout(function () {
        window.location.replace(origin + dir + '/ot-classroom-index.html');
    }, delay)
}
// 回到讲堂首页 - 添加历史
function backIndex2(delay) {
    delay = delay || 0;
    setTimeout(function () {
        window.location.href = origin + dir + '/ot-classroom-index.html';
    }, delay)
}
// 获取联动列表html
function getListHtml(data, code, name, select) {
    var html = '';
    var active = select ? select : 0 // 默认选中的下标
    data.forEach(function (item, index) {
        html += '<p class="' + (index == active ? 'active' : '') + '" data-code="' + item[code] + '">' + item[name] + '</p>'
    });
    return html;
}

// 获取无数据html
function getNoDataHtml(txt) {
    txt = txt || '没有更多数据了';
    return '<div class="weui-loadmore weui-loadmore_line"><span class="weui-loadmore__tips">' + txt + '</span></div>';
}
// 获取加载更多html
function getLoadMoreHtml() {
    return '<div class="weui-loadmore"><i class="weui-loading"></i><span class="weui-loadmore__tips">正在加载</span></div>';
}
// 获取广告html
function getAdHtml(data) {
    var html = '';

    if (data.videoId) {
        html += '<div class="posRel" data-videoId="' + data.videoId + '">' +
            '<img src="' + data.file.uploadUrl + '" alt="' + data.name + '">' +
            '<i class="pub-i-play"></i>';
    } else {
        html += '<div class="posRel">' +
            '<img src="' + data.file.uploadUrl + '" alt="' + data.name + '">';
    }

    html += '</div>';
    return html;
}



// 视频播放
var player2;
// 1.3增加
let setUp = {} // 配置项
let trialSecond // 时间最大限制
let seriesFree // 课程是否免费
let courseTime // 10秒存进度 时间器
let playedPercent // 继播/秒
let coursePaid // 是否购买
$(document.body).on('click', '[data-videoId]', function (e) {
    let dom = $(e.currentTarget)
    var videoId = dom.attr('data-videoId');
    var backUrl = dom.attr('data-backUrl'); // 直播跳转路径
    if (backUrl) {
        window.location.href = backUrl
        return false
    }

    // 1.3增加
    setUp = {
        playdom: dom.attr('playdom'), // 视频播放dom的id
        height: dom.attr('height'), // 视频容器高度
        skin: Boolean(dom.attr('skin')), // 视频进度条隐藏
        stopScreen: Boolean(dom.attr('stopScreen')), // 关闭自动全屏
        monitor: Boolean(dom.attr('monitor')), // 10秒保存一次播放进度
        lessonId: dom.attr('lessonId'), // 节id
    }
    setUp.skin ? dom.siblings('.alyStop').show() : '' // 进度条隐藏 由蒙层来点击控制播放暂停
    getVideoPlayAuth(videoId)
})


// 获取视频播放凭证
function getVideoPlayAuth(videoId) {
    $.showLoading('视频加载中...');
    http('/video/getPlayAuth', {
        hasToken: false,
        data: {
            videoId: videoId
        },
        success: function (res) {
            // toast('res.code' + res.data.playAuth)
            if (res.code === '01') {
                setUp.playdom ? $('#' + setUp.playdom).html('') : $('.video.popup').show().find('.cont').hide().html('')

                player2 = new Aliplayer({
                    id: setUp.playdom ? setUp.playdom : 'player',
                    vid: videoId,
                    playauth: res.data.playAuth,
                    useH5Prism: true,
                    autoplay: true,
                    playsinline: 'true',
                    preload: true,
                    format: "m3u8",
                    mediaType: 'video',
                    controlBarVisibility: 'click',
                    x5_orientation: 'landscape',
                    x5_type: 'H5',
                    winth: '100%',
                    height: setUp.height ? setUp.height : '200px',
                    skinLayout: setUp.skin ? skinLayoutoff : skinLayout,
                    components: trialSecond && !seriesFree && !coursePaid ? [{ // 试看组件的属性
                        name: 'PreviewVodComponent',
                        type: AliPlayerComponent.PreviewVodComponent,
                        args: [Number(trialSecond), '#endPreviewTemplate', '购买课程，观看完整视频']
                    }] : []
                }, function (player2) {
                    var close_btn = document.querySelector('.players_tip_cont')
                    close_btn.addEventListener('click', function () {
                        player2.getComponent('PreviewVodComponent').closePreviewLayer()
                    })
                });
                player2.on('ready', function (err) {
                    player2.play();
                    // 跳转播放
                    playedPercent ? player2.seek(Number(playedPercent)) : 0
                    setCourseLearn(true)
                    // 关闭自动全屏
                    setUp.stopScreen ? '' : player2.fullscreenService.requestFullScreen();
                    setTimeout(function () {
                        $('.video.popup').show().find('.cont').show();
                    }, 100)
                    $.hideLoading();
                    // 每10秒上传观看进度
                    setUp.monitor && getCookie('userId') ? setCourseLearn() : ''
                    // 关闭试看提示
                    if (player2.isPreview()) {
                        setTimeout(function () {
                            $('.preview-component-tip').hide()
                        }, 3000)
                    }
                })

                // 时间限制
                // if (trialSecond && !seriesFree) {
                //     console.log('试看时间' + trialSecond)
                //     player2.setPreviewTime(Number(trialSecond))
                // }
            } else {
                $.hideLoading();
            }
        },
        fail: function () {
            $.hideLoading();
        }
    })
}

// 
function setCourseLearn(reset) {
    if (reset) {
        playedPercent = 0
        posthttp('/course_learn', {
            data: {
                type: 'c',
                user: getCookie('userId'),
                lesson: setUp.lessonId,
                duration: player2.getDuration(),
                played: 0
            },
            success: function (res) {
                console.log('重置时间', player2.getDuration(), player2.getCurrentTime())
            }
        })
        return false
    }
    console.log('开始记录', setUp)
    courseTime = setInterval(function () {
        // 播放完毕 / 暂停 不提交信息
        if (player2.getStatus() == 'ended') {
            clearInterval(courseTime)
            return false
        } else if (player2.getStatus() == 'pause') {
            return false
        }
        posthttp('/course_learn', {
            data: {
                type: 'c',
                user: getCookie('userId'),
                lesson: setUp.lessonId,
                duration: player2.getDuration(),
                played: player2.getCurrentTime()
            },
            success: function (res) {
                console.log(player2.getDuration(), player2.getCurrentTime())
            }
        })
    }, 10000)
}

// 弹窗关闭
$(document.body).on('click', '.popup', function (e) {
    $(e.currentTarget).hide();
    if (player2) {
        player2.dispose();
    }
})

$(document.body).on('click', '.popup .cont', function (e) {
    // e.stopPragatation();
    return false;
})

// 微信一键注册
function getWxopenid() {
    if (code === '' || code == null) {
        var thisUrl = window.location.href;
        thisUrl = encodeURIComponent(thisUrl);
        var theWx = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appId + '&redirect_uri=';
        var url = theWx + thisUrl + '&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect';
        window.location.href = url;
    }
}
function getOpenid() {
    var aJson = {
        'jsCode': code,
    };
    $.ajax({
        url: host + '/user/goVxLogin',
        method: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(aJson),
        success: function (res) {
            if (res.code == '01') {
                var data = res.data;
                toast('授权成功')
                if (data.type === '1') {
                    setTimeout(function () {
                        window.location.href = 'login-bind-phone.html?openid=' + data.openid;
                    }, 1000)
                } else {
                    setCookie('token', res.data.token);
                    setCookie('userId', res.data.userId, 1);
                    localStorage.setItem("mobile", res.data.loginMobile);
                    backIndex(1000)
                }
            } else {
                toast(res.message);
            }
        }
    });
}

function xcxConfig() {
    //初始化微信分享参数--开始
    var wxappid = "";
    var timestamp = "";
    var nonceStr = "";
    var signature = "";
    initWxShareParams();
    function initWxShareParams() {
        var requestUrl = window.location.href;
        $.ajaxSetup({
            async: false,
        });
        http('/user/getSign', {
            hasToken: false,
            data: {
                "url": requestUrl
            },
            success: function (res) {
                if (res.code === '01') {
                    var iData = res.data;
                    wxappid = iData.appid;
                    timestamp = iData.timestamp;
                    nonceStr = iData.noncestr;
                    signature = iData.signature;

                    //微信分享--开始
                    wx.config({
                        debug: false,
                        appId: wxappid,
                        timestamp: timestamp,
                        nonceStr: nonceStr,
                        signature: signature,
                        jsApiList: [
                            'updateTimelineShareData',
                            'updateAppMessageShareData'
                        ],
                        openTagList: ['wx-open-launch-weapp']
                    });
                }
            }
        })
    }
}

// 跳转微信小程序弹窗关闭
$(document.body).on('click', '.weapp-popup', function (e) {
    $(e.currentTarget).css('top', '200%');
})
$(document.body).on('click', '.weapp-popup .cont', function (e) {
    e.stopPragatation();
})

function getWeappHtml(url) {
    url = url || 'pages/index/index';
    return '<wx-open-launch-weapp class="a" username="gh_3baf85f7018e" path="' + url + '" style="position:absolute;left:0;top:0;width:100%;padding:0;margin:0;opacity:0;z-index:2;">' +
        '<template> ' +
        '<style>' +
        '.btn {width:100vw;height:200vw;}' +
        '.btn:focus{outline: none;}' +
        '</style>' +
        '<button class="btn">跳转小程序</button>' +
        '</template>' +
        '</wx-open-launch-weapp>'
}

function getNumberHtml(num) {
    return num > 99 ? '<span class="number">99</span><span>+</span>' : '<span class="number">' + num + '</span>';
}

// 页面重定向到https
var ishttps = 'https:' == window.location.protocol ? true : false;
if (!ishttps) {
    url = window.location.href.replace('http', 'https');
    window.location.replace(url)
}

// bar
// back 返回 close 关闭 search 搜索 menu 更多 transparent 透明
(function initBar() {
    let title = $('.pub_bar').attr('title') ? $('.pub_bar').attr('title') : ''
    let left = $('.pub_bar').attr('left') ? $('.pub_bar').attr('left').split(',') : []
    let right = $('.pub_bar').attr('right') ? $('.pub_bar').attr('right').split(',') : []

    $('.pub_bar').attr('transparent') == 'true' && $('.pub_bar').addClass('active')

    $('.pub_bar').html(`<div class="pub_bar_cont"><div class="pub_bar_left"></div>
                        <div>${title}</div>
                        <div class="pub_bar_right"></div></div>`)

    for (let i in left) {
        $('.pub_bar_left').append(`<div id="${left[i]}"></div>`)
    }
    for (let i in right) {
        $('.pub_bar_right').append(`<div id="${right[i]}"></div>`)
    }
})()

$(document).on('click', '#back', function () {
    history.go(-1)
})


// 打开评论
$(document).on('click', '.comment', function () {
    loading = false
    $(".comment_cont").slideDown()
    $('body').css('overflow-y', 'hidden')
    $(".swiper-container").addClass('swiper-no-swiping')
})

// 关闭评论
$(document).on('click', '.comment_close', function () {
    $(".comment_cont").slideUp()
    $('body').css('overflow-y', 'auto')
    $(".swiper-container").removeClass('swiper-no-swiping')
})

// video视频播放

$(document).on('click', '.play', function () {
    $(this).hide()
    // $(".doctorInfo_img").trigger('play')
    $(this).siblings('.poster').hide()
})

// tab切换
var status = 0
$(document).on('click', '.tabs_item', function () {
    let index = $(this).index()
    $('.nolist').hide()
    status = index
    loading = false
    $(this).addClass('active').siblings().removeClass("active")
    $(this).parent().next('.relevant_listing').find('.relevant_list').eq(index).show().siblings().hide()
})


// 默认配置项
let skinLayout = [
    { name: "bigPlayButton", align: "blabs", x: 30, y: 80 },
    {
        name: "H5Loading", align: "cc"
    },
    { name: "errorDisplay", align: "tlabs", x: 0, y: 0 },
    { name: "infoDisplay" },
    { name: "tooltip", align: "blabs", x: 0, y: 56 },
    { name: "thumbnail" },
    {
        name: "controlBar", align: "blabs", x: 0, y: 0,
        children: [
            { name: "progress", align: "blabs", x: 0, y: 44 },
            { name: "playButton", align: "tl", x: 15, y: 12 },
            { name: "timeDisplay", align: "tl", x: 10, y: 7 },
            { name: "fullScreenButton", align: "tr", x: 10, y: 12 },
            { name: "subtitle", align: "tr", x: 15, y: 12 },
            { name: "setting", align: "tr", x: 15, y: 12 },
            { name: "volume", align: "tr", x: 5, y: 10 }
        ]
    }
]

// 关闭进度条的配置项
let skinLayoutoff = [
    { name: "bigPlayButton", align: "blabs", x: 30, y: 80 },
    { name: "H5Loading", align: "cc" },
    { name: "errorDisplay", align: "tlabs", x: 0, y: 0 },
    { name: "infoDisplay" },
    { name: "tooltip", align: "blabs", x: 0, y: 56 },
    { name: "thumbnail" },
    {
        name: "controlBar", align: "blabs", x: -100, y: -100,
        children: [
            { name: "playButton", align: "tl", x: 15, y: 12 },
        ]
    }
]


// 时间戳 转 2020-02-20 20:20:02
function add0(m) { return m < 10 ? '0' + m : m }
function formatInfo(shijianchuo) {
    var time = new Date(parseInt(shijianchuo));
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return {
        a: y + '-' + add0(m) + '-' + add0(d),
        b: add0(h) + ':' + add0(mm)
    }
}